package com.billing.aop;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.billing.persistance.dao.IGenericDAO;
import com.billing.persistance.entities.AuditEntry;
import com.billing.persistance.entities.IBusinessEntity;

@Aspect
public class AuditAspect {

	@Autowired
	@Qualifier (value="auditDAO")
	private IGenericDAO<AuditEntry, Long> auditDAO;

	private Logger logger = Logger.getLogger(AuditAspect.class);

	@Before("isAuditable() && args(businessEntity,..)")
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void trackServiceExecution(JoinPoint point,IBusinessEntity businessEntity) throws Throwable {

		// Use the business entity here to generate the Audit bean
		StringBuilder sb = new StringBuilder();
		sb.append("Auditing method: "  + point.getSignature().getName());
		sb.append("Business Entity: " + '\n');
		sb.append(businessEntity);
		
		System.out.println(sb.toString());
		logger.debug(sb.toString());
		
		AuditEntry entry = new AuditEntry();
		entry.setAction(sb.toString());
		// TODO: Set owner as a technical user
		// entry.setBillOwner(user)
		auditDAO.create(entry);
	}

	@Pointcut("@annotation(com.billing.aop.Auditable)")
	public void isAuditable() {
	}

}